﻿using System;
using BizControl.Library.Security;
using Csla;
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Prism.Modularity;
using BizControl.Presentation.Infrastructure.Constants;
using BizControl.Library.BusinessObjects.Models;
using BizControl.Library.BusinessObjects.People;
using Microsoft.Practices.Prism.Commands;
using System.Windows.Input;
using System.Windows;

namespace BizControl.Presentation.Shell.ViewModels
{
  [Export]
  public class ShellViewModel : IPartImportsSatisfiedNotification
  {
    private IModuleManager _moduleManager;
    private IRegionManager _regionManager;

    private readonly DelegateCommand _logoutCommand;
    private readonly DelegateCommand _exitCommand;

    [ImportingConstructor]
    public ShellViewModel(IRegionManager regionManager, IModuleManager moduleManager)
    {
      _regionManager = regionManager;
      _moduleManager = moduleManager;
      _logoutCommand = new DelegateCommand(Logout);
      _exitCommand = new DelegateCommand(Exit);
    }

    private void Logout()
    {
      BizControlPrincipal.Logout();
      App.IsLoggingOut = true;
      App.Current.MainWindow.Close();
    }

    private void Exit()
    {
      App.IsLoggingOut = false;
      App.Current.MainWindow.Close();
    }

    public ICommand LogoutCommand
    {
      get { return _logoutCommand; }
    }

    public ICommand ExitCommand
    {
      get { return _exitCommand; }
    }

    public PersonBO CurrentUser 
    {
      get { return ((BizControlPrincipal)ApplicationContext.User).Person; }
    }

    public ModelBO CurrentModel
    {
      get { return ((BizControlPrincipal)ApplicationContext.User).Model; }
    }

    public void OnImportsSatisfied()
    {
      this._moduleManager.LoadModuleCompleted +=
          (s, e) =>
          {
            if (e.ModuleInfo.ModuleName == typeof(ActivitiesModule.ActivitiesModule).FullName)
            {
              this._regionManager.RequestNavigate(ShellRegionNames.MainContentRegion, ViewNames.ActivitiesViewName);
            }
          };
    }
  }
}